package com.example.spider.provider.why10w.thn21;

import com.example.spider.provider.why10w.AbstractWhy10wDetailResultHandler;
import com.example.spider.provider.why10w.dto.Why10wDetailTask;
import com.example.spider.provider.why10w.dto.WhyTaskResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理 thn21 详情页结果
 * <p>
 * // 该网站一页多个
 *
 * @author lym
 */
@Slf4j
@Component
public class Thn21DetailResultHandler extends AbstractWhy10wDetailResultHandler {


    private static WhyTaskResult buildResult(Why10wDetailTask task, String id, String title, String content) {
        String category = task.getFirstCategory();
        return WhyTaskResult.builder()
                .id(id)
                .title(title)
                .url(task.getUrl())
                .categoryList(category == null ? Collections.emptyList() : List.of(category))
                .tagList(Collections.emptyList())
                .imageInfoList(Collections.emptyList())
                .content(content)
                .source(task.getSource())
                .build();
    }

    @Override
    public void doHandle(Why10wDetailTask task, String html) {

        // 要解析的太多了，先截取期望部分，避免每次解析全部html

        //获取html的文档对象
        Document doc = Jsoup.parse(html);
        //获取页面下id="content"的标签
        Element contentElement = doc.getElementById("V");
        //获取页面下的a标签
        Elements pList = contentElement.getElementsByTag("p");
        // title
        pList.remove(0);
        // lastPage / next
        pList.remove(pList.size() - 1);

        if (CollectionUtils.isEmpty(pList)) {
            // 结束了 部分文档404，内容缺失，忽略
            log.error("thn21Detail invalid. Task:{}", task.getUrl());
            return;
        }

        String url = task.getUrl();
        String id = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));


        if ("你身边的科技".equals(task.getFirstCategory())) {
            // 多个
            StringBuilder contentBuilder = new StringBuilder();
            int index = 0;
            String idWithIndex = null;
            String title = null;
            for (int i = 0; i < pList.size(); i++) {
                Element element = pList.get(i);
                boolean isTitle = CollectionUtils.isNotEmpty(element.getElementsByTag("strong"));
                if (isTitle) {
                    // save last
                    if (index != 0) {
                        WhyTaskResult result = buildResult(task, idWithIndex, title, contentBuilder.toString());
                        repository.addResult(result);
                    }
                    // createThis
                    idWithIndex = id + "_" + index;
                    index++;
                    title = element.text();
                    contentBuilder = new StringBuilder();
                } else {
                    contentBuilder.append(element.text());
                }
            }
            //save last
            WhyTaskResult result = buildResult(task, idWithIndex, title, contentBuilder.toString());
            repository.addResult(result);
        } else {
            // 单个
            List<String> pTextList = pList.stream().map(Element::text).collect(Collectors.toList());
            String title = task.getTitle();
            String content = String.join("", pTextList);

            WhyTaskResult result = buildResult(task, id, title, content);
            repository.addResult(result);
        }
        // ***********************


        repository.saveHtml(task, html);
    }
}
